package cn.itcast.demo.web;

import cn.itcast.demo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("hello")
@Slf4j
public class HelloController {

    @GetMapping("sync")
    public User getUserSync() {
        log.info("sync 开始执行");
        User user = createUser();
        log.info("sync 执行完毕");
        return user;
    }

    @GetMapping("mono")
    public Mono<User> getUserMono(){
        log.info("mono 开始执行");
        Mono<User> mono = Mono.fromSupplier(this::createUser);
        log.info("mono 执行完毕");
        return mono;
    }

    private User createUser() {
        // 模拟业务执行耗时
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 创建user并返回
        return User.of("Rose", 18);
    }

    @GetMapping("flux")
    public Flux<User> getUserFlux(){
        log.warn("flux 开始执行");
        Flux<User> userFlux = createUserFlux();
        log.warn("flux 执行完毕");
        return userFlux;
    }

    @GetMapping(value = "stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getUserFluxStream(){
        log.warn("stream 开始执行");
        Flux<User> userFlux = createUserFlux();
        log.warn("stream 执行完毕");
        return userFlux;
    }

    private Flux<User> createUserFlux(){
        return Flux.interval(Duration.ofSeconds(1))// 每隔1秒发射一个long元素
                //.take(3) // 我只要前3个元素
                .map(i -> User.of("test_" + i, i.intValue() + 20));// 把数据转为User
    }
}
